#coding:utf-8
from django.http import HttpResponse,HttpResponseRedirect,Http404
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from forms import UploadFileForm,GetFileForm
from Nodecontrol.models import nodegroup
from Cfgupload.models import md5model
import os
import time
import commands
from Nodecontrol.models import node_info
import threading

def handle_uploaded_file(f,zone):
    '''
    上传文件
    '''
    file_name = ""

    try:
        #path = "upload/file" + time.strftime('/%Y%m%d')
        path = "upload/file/" + zone
        print path
        if not os.path.exists(path):
            os.makedirs(path)
        file_name = path +os.sep+f.name
        destination = open(file_name, 'wb+')
        for chunk in f.chunks():
            destination.write(chunk)
        destination.close()
    except Exception, e:
        print e
    return file_name

def rsyncdel(request,iplist,dir):
    for ip in iplist:
        attempts = 0
        success = False
        while attempts < 3 and not success:
            res,output = commands.getstatusoutput('/usr/bin/rsync -azv --delete %s rsync://%s/cdncfg'%(dir,ip.NodeIP))
            if res==0:
                return 0
                success = True
            else:
                attempts += 1
        if attempts==3:
            return output



@login_required(login_url="/login/")
def upload_file(request):
    if request.method == 'POST':
       form = UploadFileForm(request.POST, request.FILES)
       if form.is_valid():
          nodeg = request.POST.get('nodegroup')

          print nodeg
          handle_uploaded_file(request.FILES['file'],nodeg)
          path = "upload/file/" + nodeg
          node_list = node_info.objects.filter(nodegroup=nodeg)
          res = rsyncdel(node_list,path)
          if res == 0:
              return HttpResponseRedirect('/upload')
          else:
              return render(request,'err.html', locals())
    else:
       group_list = nodegroup.objects.all()
       form = UploadFileForm()
    return render(request,'upload.html', locals())

def downpack(packname,node):
    print node,packname
    if  md5model.objects.filter(nodeip=node,filename=packname):
        md5model.objects.filter(nodeip=node,filename=packname).update(md5value = 'downloading')
    else:
        md5model(nodeip=node,filename=packname,md5value='downloading').save()
    res = os.system("wget http://cdndownload.99.com/%s -e http_proxy=%s:5000 -P /data/download/%s -O %s"%(packname,node,node,packname))
    if res:
         md5model.objects.filter(nodeip=node,filename=packname).update(md5value = 'error 包不存在')
    else:
        md5v = commands.getoutput("md5sum /data/download/%s/%s"%(node,packname))
        md5v =  md5v.split()[0]
        md5model.objects.filter(nodeip=node,filename=packname).update(md5value = md5v)


@login_required(login_url="/login/")
def getpack(request):
    if request.method == 'POST':
          nodeg = request.POST.getlist('nodegroup')
          packname = request.POST.get('filename')
          print nodeg
          node_list = []
          for i in nodeg:
              print i
              node_list.append( node_info.objects.filter(nodegroup=i))
          print node_list
          threads = []
          for i in node_list:
              for node in i:
                print 'dddddddddddddddddddddd%s'%node
                t=threading.Thread(target= downpack,args=(packname,node.NodeIP))
                t.start()
                threads.append(t)
              for t in threads:
                t.join()
          group_list = nodegroup.objects.all()
          form = GetFileForm()
    else:
       group_list = nodegroup.objects.all()
       form = GetFileForm()

    return render(request,'getpack.html', locals())



@login_required(login_url="/login/")
def md5_view(request):
    md5_list = md5model.objects.all()
    return render(request, 'md5check.html',locals())

